package com.ganbo.ms.netty.simple.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author ganbo
 * @date 2022/12/8 20:34
 */
public class NClient {

    public static void main(String[] args) throws InterruptedException {


        Bootstrap serverBootstrap = new Bootstrap();
        serverBootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) {

                                System.out.println("发送成功");
                                System.out.println("==================hello ");
//                                byte[] bytes;
                                for (int i = 0; i < 10; i++) {
                                    //bytes = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//                                    ctx.writeAndFlush(bytes);
                                    ctx.channel().writeAndFlush("hello" + i);
                                }

                                ctx.fireChannelRead(ctx);
                            }
                        });
                    }
                }).connect("127.0.0.1", 8888).sync();
    }
}
